package com.ufm.user.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import com.ufm.security.pojo.Roles;
import com.ufm.security.pojo.UsersAndRoles;
import com.ufm.security.service.IRightsService;
import com.ufm.security.service.IRolesService;
import com.ufm.syslog.pojo.Syslog;
import com.ufm.syslog.service.ISyslogService;

import com.ufm.user.pojo.User;
import com.ufm.user.service.IUserService;
import com.ufm.util.PageUtil;
import com.ufm.util.TreeUtil;

@Controller
@RequestMapping("/ufmUser/*")
public class UserController {
	@Autowired  
    private IUserService userService;
	
	@Autowired
	private ISyslogService syslogService;
	
	@Autowired
	private IRolesService roleService;
	@Autowired
	private IRightsService iRightsService;

	
	@RequestMapping(value="/ufmUser/findAll")
	public String findAll(Model model,HttpServletRequest request) {
		String userName1 = request.getParameter("userName1");
		String userNumber1 = request.getParameter("userNumber1");
		String attribute1 = request.getParameter("attribute1");
		String userId1 = request.getParameter("userId1");
		
		String bloneto1 = request.getParameter("bloneto1");
		String bloneto = "";
		Integer currentPageNo = PageUtil.PAGE_NUM;
		Integer perPageNumber = PageUtil.RECORD_NUM;
		
		String currentPageNoStr = request.getParameter("currentPageNo");
		if(currentPageNoStr!=null && !"".equals(currentPageNoStr)){
			currentPageNo = Integer.parseInt(currentPageNoStr);
		}
		
		String perPageNumberStr = request.getParameter("perPageNumber");
		if(perPageNumberStr!=null && !"".equals(perPageNumberStr)){
			perPageNumber = Integer.parseInt(perPageNumberStr);
		}
		
		if(bloneto1!=null && !"".equals(bloneto1)){
			bloneto = bloneto1.replace("d", "");
		}
		
		Map params = new HashMap();
		params.put("userName", userName1);
		params.put("userNumber", userNumber1);
		params.put("attribute1", attribute1);
		params.put("userId1", userId1);
		params.put("bloneto", bloneto);
		
		
		List<User> usersTemp = userService.findAll(params);
		List<User> users = PageUtil.getPageList(usersTemp, currentPageNo, perPageNumber);
		
		int total = usersTemp.size();
		
		model.addAttribute("users", users);
		model.addAttribute("userName1", userName1);
		model.addAttribute("userNumber1", userNumber1);
		model.addAttribute("attribute1", attribute1);
		model.addAttribute("bloneto", bloneto);
		model.addAttribute("userId1", userId1);
		
		model.addAttribute("currentPageNo", currentPageNo);
		model.addAttribute("count", total == 0?1:total%perPageNumber == 0?total/perPageNumber:total/perPageNumber+1);
		
		return "user/findAll";
	}
	
	/*@RequestMapping(value="/ufmUser/addUser")
	public String addUser(Model model) {
		
		List<String> emailList = userService.findAllEmail();
		List<String> userLoginList = userService.findAllUserLogin();
		
		List<Dept> deptList = iDeptService.findAllDept();
		model.addAttribute("deptList",deptList);
		
		List<Dictionary> sexList = dictService.findDictByKeyName("性别");
		model.addAttribute("sexList", sexList);
		List<Dictionary> statusList = dictService.findDictByKeyName("员工状态");
		model.addAttribute("statusList", statusList);
		List<Dictionary> jobList = dictService.findDictByKeyName("职位");
		model.addAttribute("jobList", jobList);
		List<Dictionary> paperList = dictService.findDictByKeyName("证件名称");
		model.addAttribute("paperList", paperList);
		List<Dictionary> educationList = dictService.findDictByKeyName("学历");
		model.addAttribute("educationList", educationList);
		List<Dictionary> degreeList = dictService.findDictByKeyName("学位");
		model.addAttribute("degreeList", degreeList);
		
		List<Roles> roleList = roleService.findAll(new HashMap());
		model.addAttribute("roleList", roleList);
		
		model.addAttribute("emailList", emailList);
		model.addAttribute("userLoginList", userLoginList);
		
		return "user/addUser";
	}*/
	
	/*@RequestMapping(value="/ufmUser/addNew")
	public String addNew(User user1, Model model, HttpServletRequest request) {
		User user = user1;
		user.setAttribute1("1");//激活用户
		user = userService.insert(user);
		dictService.updateDict(user.getStatus());
		dictService.updateDict(Long.parseLong(user.getJobid()));
		dictService.updateDict(Long.parseLong(user.getPaper()));
		dictService.updateDict(Long.parseLong(user.getEducation()));
		dictService.updateDict(Long.parseLong(user.getDegree()));
		String rolegroup = request.getParameter("rolegroup");
		String[] role = rolegroup.split(",");
		for(int i=0;i<role.length;i++){
			if(role[i] != null && !"".equals(role[i])){
				UsersAndRoles usersAndRoles =new UsersAndRoles();
				usersAndRoles.setUsers_id((int)user.getUserId());
				usersAndRoles.setRole_id(Integer.parseInt(role[i].toString()));
				iRightsService.saveRoleAndUsers(usersAndRoles);
			}
		}
		addLog(request, "人员维护", "增加人员:"+user.getUserName());
		
		return "redirect:/ufmUser/findAll";
	}*/
	
	@RequestMapping(value="/ufmUser/addNewTemp")
	public String addNewTemp(Model model) {
		User user = new User();
		user.setUserName("张三");
		user.setUserLogin("zs");
		user.setUserPwd("111111");
		user = userService.insert(user);
		
		return "redirect:/ufmUser/findAll";
	}
	
	/*@RequestMapping(value="/ufmUser/toUpdatePage")
	public String toUpdatePage(Model model, HttpServletRequest request) {
		
		String flag = request.getParameter("flag");
		String userName1 = request.getParameter("userName1");
		String userNumber1 = request.getParameter("userNumber1");
		String userId1 = request.getParameter("userId1");
		
		String bloneto1 = request.getParameter("bloneto1");
		Integer currentPageNo = PageUtil.PAGE_NUM;
		
		String currentPageNoStr = request.getParameter("currentPageNo");
		if(currentPageNoStr!=null && !"".equals(currentPageNoStr)){
			currentPageNo = Integer.parseInt(currentPageNoStr);
		}
		
		
		model.addAttribute("userName1", userName1);
		model.addAttribute("userNumber1", userNumber1);
		model.addAttribute("currentPageNo", currentPageNo);
		model.addAttribute("bloneto1", bloneto1);
		model.addAttribute("userId1", userId1);
		model.addAttribute("flag", flag);
		
		Long userId = 0L;
		if(flag!=null && !"".equals(flag)){
			UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			User userSession = userService.findByName(userDetails.getUsername());
			userId = userSession.getUserId();
		}else{
			userId = Long.parseLong(request.getParameter("userId"));
		}
		User user = new User();
		user = userService.findUserById(userId);
		
		model.addAttribute("user", user);
		
		List<String> emailList = userService.findAllEmail();
		List<String> userLoginList = userService.findAllUserLogin();
		
		model.addAttribute("emailList", emailList);
		model.addAttribute("userLoginList", userLoginList);
		
		List<Dept> deptList = iDeptService.findAllDept();
		model.addAttribute("deptList",deptList);
		
		List<Dictionary> sexList = dictService.findDictByKeyName("性别");
		model.addAttribute("sexList", sexList);
		List<Dictionary> statusList = dictService.findDictByKeyName("员工状态");
		model.addAttribute("statusList", statusList);
		List<Dictionary> jobList = dictService.findDictByKeyName("职位");
		model.addAttribute("jobList", jobList);
		List<Dictionary> paperList = dictService.findDictByKeyName("证件名称");
		model.addAttribute("paperList", paperList);
		List<Dictionary> educationList = dictService.findDictByKeyName("学历");
		model.addAttribute("educationList", educationList);
		List<Dictionary> degreeList = dictService.findDictByKeyName("学位");
		model.addAttribute("degreeList", degreeList);
		List<Dictionary> locList = dictService.findAllDict();
		model.addAttribute("locList", locList);
		List<Roles> roleList = roleService.findAll(new HashMap());
		model.addAttribute("roleList", roleList);
		List<Integer> roles = iRightsService.findRoleByUserId(userId.intValue());
		model.addAttribute("roles", roles);
		return "user/editUser";
	}*/
	
	/*@RequestMapping(value="/ufmUser/updateUser")
	public String updateUser(User user1, Model model, HttpServletRequest request) {
		
		//修改个人信息标志
		String flag = request.getParameter("flag");
		
		String userName1 = request.getParameter("userName1");
		String userNumber1 = request.getParameter("userNumber1");
		String userId1 = request.getParameter("userId1");
		
		String bloneto1 = request.getParameter("bloneto1");
		Integer currentPageNo = PageUtil.PAGE_NUM;
		
		String currentPageNoStr = request.getParameter("currentPageNo");
		if(currentPageNoStr!=null && !"".equals(currentPageNoStr)){
			currentPageNo = Integer.parseInt(currentPageNoStr);
		}
		
		
		model.addAttribute("userName1", userName1);
		model.addAttribute("userNumber1", userNumber1);
		model.addAttribute("currentPageNo", currentPageNo);
		model.addAttribute("bloneto1", bloneto1);
		model.addAttribute("userId1", userId1);
		
		
		User user = user1;
		userService.update(user);
		dictService.updateDict(user.getStatus());
		dictService.updateDict(Long.parseLong(user.getJobid()));
		dictService.updateDict(Long.parseLong(user.getPaper()));
		dictService.updateDict(Long.parseLong(user.getEducation()));
		dictService.updateDict(Long.parseLong(user.getDegree()));
		
		String rolegroup = request.getParameter("rolegroup");
		if(rolegroup!=null && !"".contains(rolegroup)){
			String[] role = rolegroup.split(",");
			iRightsService.deleteRoleByUserId((int)user.getUserId());
			for(int i=0;i<role.length;i++){
				if(role[i] != null && !"".equals(role[i])){
					UsersAndRoles usersAndRoles =new UsersAndRoles();
					usersAndRoles.setUsers_id((int)user.getUserId());
					usersAndRoles.setRole_id(Integer.parseInt(role[i].toString()));
					iRightsService.saveRoleAndUsers(usersAndRoles);
				}
			}
		}
		
		addLog(request, "人员维护", "修改人员:"+user.getUserName());
		
		if(flag!=null && !"".equals(flag)){
			return "/waitTask/findAll";
		}else{
			return "redirect:/ufmUser/findAll";
		}
	}*/
	
	/*@RequestMapping(value="/ufmUser/lookUser")
	public String lookUser(Model model, HttpServletRequest request) {
		
		String userName1 = request.getParameter("userName1");
		String userNumber1 = request.getParameter("userNumber1");
		String userId1 = request.getParameter("userId1");
		
		String bloneto1 = request.getParameter("bloneto1");
		Integer currentPageNo = PageUtil.PAGE_NUM;
		
		String currentPageNoStr = request.getParameter("currentPageNo");
		if(currentPageNoStr!=null && !"".equals(currentPageNoStr)){
			currentPageNo = Integer.parseInt(currentPageNoStr);
		}
		
		
		model.addAttribute("userName1", userName1);
		model.addAttribute("userNumber1", userNumber1);
		model.addAttribute("currentPageNo", currentPageNo);
		model.addAttribute("bloneto1", bloneto1);
		model.addAttribute("userId1", userId1);
		
		Long userId = Long.parseLong(request.getParameter("userId").toString());
		User user = new User();
		user = userService.findUserById(userId);
		
		model.addAttribute("user", user);
		
		List<Dept> deptList = iDeptService.findAllDept();
		model.addAttribute("deptList",deptList);
		
		List<Dictionary> sexList = dictService.findDictByKeyName("性别");
		model.addAttribute("sexList", sexList);
		List<Dictionary> statusList = dictService.findDictByKeyName("员工状态");
		model.addAttribute("statusList", statusList);
		List<Dictionary> jobList = dictService.findDictByKeyName("职位");
		model.addAttribute("jobList", jobList);
		List<Dictionary> paperList = dictService.findDictByKeyName("证件名称");
		model.addAttribute("paperList", paperList);
		List<Dictionary> educationList = dictService.findDictByKeyName("学历");
		model.addAttribute("educationList", educationList);
		List<Dictionary> degreeList = dictService.findDictByKeyName("学位");
		model.addAttribute("degreeList", degreeList);
		List<Dictionary> locList = dictService.findAllDict();
		model.addAttribute("locList", locList);
		List<Roles> roleList = roleService.findAll(new HashMap());
		model.addAttribute("roleList", roleList);
		List<Integer> roles = iRightsService.findRoleByUserId(userId.intValue());
		model.addAttribute("roles", roles);
		return "user/lookUser";
	}*/
	
	@RequestMapping(value="/ufmUser/deleteAll")
	public String deleteAll(@RequestParam("selIds") String selIds, HttpServletRequest request) {
		String[] ids = selIds.split(",");
		userService.deleteMore(ids,request);
		
		return "redirect:/ufmUser/findAll";
	}
	
	public void addLog(HttpServletRequest request, String moduleName, String action){
		//User userSession = (User)request.getSession().getAttribute("user");
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		User userSession = userService.findByName(userDetails.getUsername());
		Syslog syslog = new Syslog(moduleName, action, 1, userSession.getUserId(), userSession.getUserName(), request.getRemoteAddr(), new Date());
		syslogService.insert(syslog);
	}
	
	@RequestMapping(value="/hasRight")
	public @ResponseBody List<String> hasRight(Model model,HttpServletRequest request) {
		String userLoginName = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
		return userService.hasRight(userLoginName);
	}

	/*@RequestMapping(value="/getUserInfo")
	public @ResponseBody Map getUserInfo(Model model,HttpServletRequest request) {
		String userLoginName = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
		User userSession = userService.findByName(userLoginName);
		Dept dept = iDeptService.findDeptById(Long.parseLong(userSession.getBloneto()));
		Map map = new HashMap();
		map.put("deptName", dept.getM3().trim());
		map.put("userName", userSession.getUserName().trim());
		return map;
	}*/
	
	/*@RequestMapping(value="/getUserInfoBottom")
	public @ResponseBody Map getUserInfoBottom(Model model,HttpServletRequest request) {
		String userLoginName = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
		User userSession = userService.findByName(userLoginName);
		Dept dept = iDeptService.findDeptById(Long.parseLong(userSession.getBloneto()));
		Map map = new HashMap();
		map.put("userName", userLoginName);
		map.put("deptName", dept.getM3());
		return map;
	}*/
	
	/*@RequestMapping(value="/getLocationTree")
	public @ResponseBody List<TreeUtil> getDeptListTree(Model model,HttpServletRequest request) {
		List<TreeUtil>  res = new ArrayList<TreeUtil>();
		List<Dictionary> locationList = dictService.findDictByKeyName("所属地区");
		List<Dictionary> locationList2 = dictService.findDictByKeyNameAndPid("所属地区");
		String locIds  = request.getParameter("locIds");
		if(locationList!=null && locationList.size()>0){
			for(int i=0;i<locationList.size();i++){
				Dictionary dict = locationList.get(i);
				TreeUtil t1 =new TreeUtil(dict.getZ1()+"",dict.getZ2()+"",dict.getZ3(),true);
				if(locIds.equals(dict.getZ1()+"")){
					t1.setChecked(true);
				}
				res.add(t1);
			}
		}
		
		if(locationList2!=null && locationList2.size()>0){
			for(int i=0;i<locationList2.size();i++){
				Dictionary dict = locationList2.get(i);
				TreeUtil t1 =new TreeUtil(dict.getZ1()+"",dict.getZ2()+"",dict.getZ3(),true);
				if(locIds.equals(dict.getZ1()+"")){
					t1.setChecked(true);
				}
				res.add(t1);
			}
		}
		
		return res;
	}*/

	@RequestMapping(value="/changePwd")
	public @ResponseBody String changePwd(Model model,HttpServletRequest request) {
		String pwd = request.getParameter("pwd");
		String newPwd = request.getParameter("newPwd");
		String userLoginName = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
		User userSession = userService.findByName(userLoginName);
		if(userSession.getUserPwd().equals(pwd)){
			userSession.setUserPwd(newPwd);
			userService.updatePwd(userSession);
			return "1";
		}else{
			return "0";
		}
	}
	
	@RequestMapping(value="/getGunDongBoBao")
	public @ResponseBody Map getGunDongBoBao(Model model,HttpServletRequest request) {
		String userLoginName = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
		User userSession = userService.findByName(userLoginName);
		String getGunDongBoBao = userService.getGunDongBoBao();
		Map map = new HashMap();
		map.put("getGunDongBoBao", getGunDongBoBao);
		return map;
	}

	//得到当前点击菜单的ID，然后改变颜色
	@RequestMapping(value="/changeMenu")
	public @ResponseBody void changeMenu(Model model,HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		String pwd = URLDecoder.decode(request.getParameter("MenuId"),"utf-8");
		request.getSession().setAttribute("menuId",pwd);
	}
	
/*	@RequestMapping(value="/ufmUser/registUser")
	public String registUser(Model model) {
		
		List<String> emailList = userService.findAllEmail();
		List<String> userLoginList = userService.findAllUserLogin();
		
		List<Dept> deptList = iDeptService.findAllDept();
		model.addAttribute("deptList",deptList);
		
		List<Dictionary> sexList = dictService.findDictByKeyName("性别");
		model.addAttribute("sexList", sexList);
		List<Dictionary> statusList = dictService.findDictByKeyName("员工状态");
		model.addAttribute("statusList", statusList);
		List<Dictionary> jobList = dictService.findDictByKeyName("职位");
		model.addAttribute("jobList", jobList);
		List<Dictionary> paperList = dictService.findDictByKeyName("证件名称");
		model.addAttribute("paperList", paperList);
		List<Dictionary> educationList = dictService.findDictByKeyName("学历");
		model.addAttribute("educationList", educationList);
		List<Dictionary> degreeList = dictService.findDictByKeyName("学位");
		model.addAttribute("degreeList", degreeList);
		
		List<Roles> roleList = roleService.findAll(new HashMap());
		model.addAttribute("roleList", roleList);
		
		model.addAttribute("emailList", emailList);
		model.addAttribute("userLoginList", userLoginList);
		
		return "user/registUser";
	}*/
	
	@RequestMapping(value="/ufmUser/addNewRegist")
	public @ResponseBody void addNewRegist(User user1, Model model, HttpServletRequest request) {
		User user = user1;
		user.setAttribute1("0");
		user = userService.insert(user);
		
		//roleId = 15 部门报送角色
		UsersAndRoles usersAndRoles =new UsersAndRoles();
		usersAndRoles.setUsers_id((int)user.getUserId());
		usersAndRoles.setRole_id(15);
		iRightsService.saveRoleAndUsers(usersAndRoles);
		
		addLog(request, "人员维护", "增加注册人员:"+user.getUserName());
	}
	
	@RequestMapping(value="/ufmUser/registAll")
	public String registAll(@RequestParam("selIds") String selIds, HttpServletRequest request) {
		String[] ids = selIds.split(",");
		userService.registMore(ids,request);
		
		return "redirect:/ufmUser/findAll";
	}
	
}